<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>量表测评 - 心理咨询系统</title>
    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
    <link href="{{ url_for('static', filename='css/bootstrap-icons.css') }}" rel="stylesheet">
    <style>
        .assessment-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .scale-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .progress-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 20px;
        }
        
        .content-card {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border-left: 4px solid #667eea;
        }
        
        .option-card {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .option-card:hover {
            border-color: #667eea;
            background-color: #f8f9ff;
        }
        
        .option-card.selected {
            border-color: #667eea;
            background-color: #667eea;
            color: white;
        }
        
        .loading {
            text-align: center;
            padding: 50px;
        }
        
        .navigation-buttons {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
        }
    </style>
</head>
<body>
    <div class="assessment-container">
        <!-- 量表信息头部 -->
        <div class="scale-header">
            <h1 id="scaleTitle">量表测评</h1>
            <p id="scaleDescription" class="mb-0 opacity-90">专业心理量表评测服务</p>
        </div>
        
        <!-- 进度条 -->
        <div id="progressSection" class="progress-section d-none">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <span class="fw-bold">测评进度</span>
                <span id="progressText">0 / 0</span>
            </div>
            <div class="progress" style="height: 8px;">
                <div id="progressBar" class="progress-bar bg-primary" style="width: 0%"></div>
            </div>
        </div>
        
        <!-- 错误提示 -->
        <div id="errorAlert" class="alert alert-danger d-none" role="alert">
            <i class="bi bi-exclamation-triangle me-2"></i>
            <span id="errorMessage"></span>
        </div>
        
        <!-- 主要内容区域 -->
        <div id="mainContent">
            <div class="content-card">
                <div class="loading">
                    <div class="spinner-border text-primary mb-3" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <h5>正在加载量表信息...</h5>
                    <p class="text-muted">请稍候</p>
                </div>
            </div>
        </div>
    </div>

    <script src="{{ url_for('static', filename='js/bootstrap.bundle.min.js') }}"></script>
    <script>
        // 全局变量
        const scaleId = {{ scale_id }};
        let assessmentData = null;
        let currentQuestionIndex = 0;
        let selectedAnswer = null;
        let selectedAnswers = []; // 用于多选题
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('量表测评页面加载 - Scale ID:', scaleId);
            loadScaleInfo();
        });
        
        // 加载量表信息
        async function loadScaleInfo() {
            try {
                const response = await fetch('/api/scales/' + scaleId);
                const data = await response.json();
                
                if (data.success) {
                    const scale = data.data;
                    document.getElementById('scaleTitle').textContent = scale.title || '量表测评';
                    document.getElementById('scaleDescription').textContent = scale.description || '请仔细阅读每个题目并选择最符合您情况的答案';
                    showIntroduction(scale);
                } else {
                    showError('无法加载量表信息: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('加载量表信息失败:', error);
                showError('加载量表信息失败: ' + error.message);
            }
        }
        
        // 显示介绍
        function showIntroduction(scale) {
            const mainContent = document.getElementById('mainContent');
            mainContent.innerHTML = 
                '<div class="content-card">' +
                '<div class="text-center">' +
                '<i class="bi bi-clipboard-check fs-1 text-primary mb-3"></i>' +
                '<h4>' + (scale.title || '量表测评') + '</h4>' +
                '<p class="lead mb-4">' + (scale.description || '请仔细阅读每个题目并选择最符合您情况的答案') + '</p>' +
                '<div class="row text-start mb-4">' +
                '<div class="col-md-6">' +
                '<div class="d-flex align-items-center mb-2">' +
                '<i class="bi bi-question-circle text-primary me-2"></i>' +
                '<span>题目数量：' + (scale.question_count || 0) + ' 题</span>' +
                '</div>' +
                '<div class="d-flex align-items-center mb-2">' +
                '<i class="bi bi-clock text-primary me-2"></i>' +
                '<span>预计时间：' + (scale.estimated_time || 10) + ' 分钟</span>' +
                '</div>' +
                '</div>' +
                '<div class="col-md-6">' +
                '<div class="d-flex align-items-center mb-2">' +
                '<i class="bi bi-shield-check text-success me-2"></i>' +
                '<span>数据安全保护</span>' +
                '</div>' +
                '<div class="d-flex align-items-center mb-2">' +
                '<i class="bi bi-graph-up text-info me-2"></i>' +
                '<span>专业结果分析</span>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="alert alert-info">' +
                '<i class="bi bi-info-circle me-2"></i>' +
                '<strong>测评说明：</strong>本测评为匿名进行，请根据您的真实情况作答。所有数据仅用于结果分析，不会泄露个人隐私。' +
                '</div>' +
                '<div class="d-grid gap-2 d-md-block">' +
                '<button class="btn btn-primary btn-lg px-5" onclick="startAssessment()">' +
                '<i class="bi bi-play-circle me-2"></i>开始测评' +
                '</button>' +
                '<button class="btn btn-outline-secondary btn-lg px-4 ms-md-3" onclick="goBack()">' +
                '<i class="bi bi-arrow-left me-2"></i>返回' +
                '</button>' +
                '</div>' +
                '</div>' +
                '</div>';
        }
        
        // 开始测评
        async function startAssessment() {
            try {
                showLoading('正在初始化测评...');
                
                const response = await fetch('/api/assessments/anonymous', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        scale_id: scaleId,
                        basic_info: {}
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    assessmentData = data.data;
                    
                    // 显示进度条
                    document.getElementById('progressSection').classList.remove('d-none');
                    updateProgress(1, assessmentData.progress.total_questions);
                    
                    // 显示第一题
                    if (assessmentData.current_question) {
                        showQuestion(assessmentData.current_question);
                    } else {
                        showError('无法获取测评题目，请重试');
                    }
                } else {
                    showError('开始测评失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('开始测评失败:', error);
                showError('开始测评失败: ' + error.message);
            }
        }
        
        // 显示题目
        function showQuestion(question) {
            const mainContent = document.getElementById('mainContent');
            
            let optionsHtml = '';
            if (question.options && question.options.length > 0) {
                for (let i = 0; i < question.options.length; i++) {
                    const option = question.options[i];
                    const isMultiple = question.question_type === 'multiple';
                    const clickHandler = isMultiple ? 'toggleOption(' + option.id + ')' : 'selectOption(' + option.id + ')';
                    optionsHtml += 
                        '<div class="option-card" onclick="' + clickHandler + '">' +
                        '<div class="d-flex align-items-center">' +
                        '<div class="me-3"><strong>' + option.option_number + '.</strong></div>' +
                        '<div class="flex-grow-1">' + option.option_text + '</div>' +
                        '<div class="ms-3"><i class="bi bi-' + (isMultiple ? 'square' : 'circle') + '"></i></div>' +
                        '</div>' +
                        '</div>';
                }
            }
            
            mainContent.innerHTML = 
                '<div class="content-card">' +
                '<h5 class="mb-4">第 ' + question.question_number + ' 题</h5>' +
                '<h6 class="mb-4">' + question.question_text + '</h6>' +
                '<div id="optionsContainer">' + optionsHtml + '</div>' +
                '<div class="navigation-buttons">' +
                '<button type="button" class="btn btn-outline-secondary" onclick="previousQuestion()" ' + 
                (question.question_number === 1 ? 'disabled' : '') + '>' +
                '<i class="bi bi-arrow-left me-2"></i>上一题' +
                '</button>' +
                '<button type="button" class="btn btn-primary" onclick="nextQuestion()" disabled id="nextBtn">' +
                '下一题<i class="bi bi-arrow-right ms-2"></i>' +
                '</button>' +
                '</div>' +
                '</div>';
        }
        
        // 选择选项（单选）
        function selectOption(optionId) {
            // 清除之前的选择
            const options = document.querySelectorAll('.option-card');
            for (let i = 0; i < options.length; i++) {
                options[i].classList.remove('selected');
                options[i].querySelector('i').className = 'bi bi-circle';
            }
            
            // 选中当前选项
            const selectedCard = document.querySelector('[onclick="selectOption(' + optionId + ')"]');
            if (selectedCard) {
                selectedCard.classList.add('selected');
                selectedCard.querySelector('i').className = 'bi bi-check-circle-fill';
                selectedAnswer = optionId;
                selectedAnswers = []; // 清空多选数组
                
                // 启用下一题按钮
                document.getElementById('nextBtn').disabled = false;
            }
        }
        
        // 切换选项（多选）
        function toggleOption(optionId) {
            const selectedCard = document.querySelector('[onclick="toggleOption(' + optionId + ')"]');
            if (!selectedCard) return;
            
            const icon = selectedCard.querySelector('i');
            const isSelected = selectedCard.classList.contains('selected');
            
            if (isSelected) {
                // 取消选择
                selectedCard.classList.remove('selected');
                icon.className = 'bi bi-square';
                selectedAnswers = selectedAnswers.filter(id => id !== optionId);
            } else {
                // 选择
                selectedCard.classList.add('selected');
                icon.className = 'bi bi-check-square-fill';
                selectedAnswers.push(optionId);
            }
            
            selectedAnswer = null; // 清空单选变量
            
            // 如果有选择，启用下一题按钮
            document.getElementById('nextBtn').disabled = selectedAnswers.length === 0;
        }
        
        // 下一题
        async function nextQuestion() {
            // 检查是否有选择答案
            const hasAnswer = selectedAnswer !== null || selectedAnswers.length > 0;
            if (!hasAnswer) {
                alert('请选择一个答案');
                return;
            }
            
            try {
                showLoading('提交答案中...');
                
                // 根据题目类型确定提交的答案
                const submitAnswer = assessmentData.current_question.question_type === 'multiple' 
                    ? selectedAnswers 
                    : selectedAnswer;
                
                const response = await fetch('/api/assessments/anonymous/' + assessmentData.assessment_id + '/answer', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        question_id: assessmentData.current_question.id,
                        selected_options: submitAnswer,
                        time_spent: 10
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentQuestionIndex++;
                    updateProgress(currentQuestionIndex + 1, assessmentData.progress.total_questions);
                    
                    if (data.data.is_completed) {
                        showCompletion();
                    } else if (data.data.next_question) {
                        assessmentData.current_question = data.data.next_question;
                        // 重置选择状态
                        selectedAnswer = null;
                        selectedAnswers = [];
                        showQuestion(data.data.next_question);
                    }
                } else {
                    showError('提交答案失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('提交答案失败:', error);
                showError('提交答案失败: ' + error.message);
            }
        }
        
        // 显示完成
        function showCompletion() {
            const mainContent = document.getElementById('mainContent');
            mainContent.innerHTML = 
                '<div class="content-card">' +
                '<div class="text-center">' +
                '<i class="bi bi-check-circle-fill text-success" style="font-size: 4rem;"></i>' +
                '<h3 class="text-success mb-3">测评完成！</h3>' +
                '<p class="lead mb-4">恭喜您完成了整个测评，正在为您生成专业的分析报告...</p>' +
                '<button class="btn btn-primary btn-lg" onclick="viewResults()">' +
                '<i class="bi bi-file-text me-2"></i>查看测评结果' +
                '</button>' +
                '</div>' +
                '</div>';
        }
        
        // 查看结果
        function viewResults() {
            window.location.href = '/assessments/' + assessmentData.assessment_id + '/results';
        }
        
        // 上一题（简化版本）
        function previousQuestion() {
            // 简化实现，稍后完善
            alert('上一题功能正在开发中');
        }
        
        // 更新进度
        function updateProgress(current, total) {
            document.getElementById('progressText').textContent = current + ' / ' + total;
            const percentage = (current / total) * 100;
            document.getElementById('progressBar').style.width = percentage + '%';
        }
        
        // 显示加载状态
        function showLoading(message) {
            const mainContent = document.getElementById('mainContent');
            mainContent.innerHTML = 
                '<div class="content-card">' +
                '<div class="loading">' +
                '<div class="spinner-border text-primary mb-3" role="status"></div>' +
                '<h5>' + message + '</h5>' +
                '</div>' +
                '</div>';
        }
        
        // 显示错误
        function showError(message) {
            document.getElementById('errorMessage').innerHTML = message;
            document.getElementById('errorAlert').classList.remove('d-none');
        }
        
        // 返回
        function goBack() {
            window.history.back();
        }
    </script>
</body>
</html>